//
//  NetworkOperationManager+Batch.m
//  OneStoreFramework
//
//  Created by huangjiming on 6/12/15.
//  Copyright (c) 2015 OneStore. All rights reserved.
//

#import "Network.h"

@interface NetworkOperationManager()

@property(nonatomic, strong) NSMutableArray *batchOperationParams;

@end

@implementation NetworkOperationManager (Batch)

- (void)requestWithParams:(NSArray<NetworkOperationParam*> *)aParams
         andCompleteBlock:(BatchCompletionBlock)completeBlock {

    WEAK_SELF;
    NSMutableArray *operations = @[].mutableCopy;
    [aParams enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        STRONG_SELF;
        if ([obj isKindOfClass:[NetworkOperationParam class]]) {
            NSURLSessionDataTask *requestOperation = [self requestWithParam:obj];
            if (requestOperation) {
                [operations addObject:requestOperation];
            } else {
                [operations addObject:[NSNull null]];
            }
        }
    }];
    
    BatchOperaionParam *batch = [BatchOperaionParam requestWithNetworkOperationManager:self params:aParams operations:operations andCompleteBlock:^(BatchOperaionParam *batchOperationParam, NSError *anError) {
        if (completeBlock) {
            completeBlock(batchOperationParam, anError);
        }
        
        if (batchOperationParam) {
            [self.batchOperationParams removeObject:batchOperationParam];
        }
    }];
    
    if (batch) {
        [self.batchOperationParams addObject:batch];
    }
}

@end
